import React from "react";
import type guest from "@/types/guest";
import type GuestForm from "@/types/GuestForm";

export default function Edit()
{
    const [SearchParams] = useSearchParams();

    const [guestid] = useState<string|null>(SearchParams.get('guestid') ? SearchParams.get('guestid') : '');
    const [guest,SetGuest] = useState<guest>({} as guest);

    // 表单实例
    const [form] = React.UI.Form.useForm();

    const OnSubmit = async (values:GuestForm) =>
    {
        const params = {
            ...values,
            busid:React.business.id,
            id:guestid
        }

        const result = await React.http.post('/guest/edit',params);

        if(result.code === 1)
        {
            React.success(result.msg,() => React.navigate(-1));
        }else{
            React.fail(result.msg);
        }
    }

    const GetGuestInfo = async () =>
    {
        const params = {
            id:guestid,
            busid:React.business.id
        }

        const result = await React.http.post('/guest/info',params);

        if(result.code === 1)
        {
            SetGuest({...result.data});
            // 更新表单字段值
            form.setFieldsValue({
                ...result.data
            });
        }else{
            React.fail(result.msg,() => React.navigate(-1));
        }
    }

    useEffect(() =>
    {
        GetGuestInfo();
    },[guestid]);

    return (
        <>
            <React.UI.Form
                form={form}
                layout="horizontal"
                onFinish={OnSubmit}
                initialValues={guest}
                footer={
                    <React.UI.Button block type='submit' color='primary' size='large'>
                        提交
                    </React.UI.Button>
                }
            >
                {/* 昵称 */}
                <React.UI.Form.Item name="nickname" label="昵称" rules={[{ required: true }]}>
                    <React.UI.Input placeholder="请输入昵称" />
                </React.UI.Form.Item>

                {/* 手机号码 */}
                <React.UI.Form.Item name="mobile" label="手机号码" rules={[{ required: true }, { pattern: /^1[3456789]\d{9}$/, message: '手机号格式不对' }]}>
                    <React.UI.Input placeholder='请输入手机号' />
                </React.UI.Form.Item>

                {/* 性别 */}
                <React.UI.Form.Item name="gender" label="性别" rules={[{ required: true }]}>
                    <React.UI.Radio.Group>
                        <React.UI.Space direction='horizontal'>
                            <React.UI.Radio value='0'>女</React.UI.Radio>
                            <React.UI.Radio value='1'>男</React.UI.Radio>
                        </React.UI.Space>
                    </React.UI.Radio.Group>
                </React.UI.Form.Item>
            </React.UI.Form>
        </>
    )
}